package com.cloudcc.boot.utils.demo;

import com.cloudcc.boot.model.UserInfo;
import com.cloudcc.boot.utils.util.CCService;
import com.cloudcc.boot.utils.util.ServiceResult;
import com.cloudcc.client.CCObject;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class McInfoSave {
	
	private UserInfo userInfo;
	public McInfoSave (UserInfo uInfo) {
		this.userInfo = uInfo;
	}
	
	/**
	 * @author caoyx
	 * @param mcid 客户货品MC信息（销售录入）ID
	 * @param productid 产品MC信息（市场部录入）ID
	 * @param data MC明细
	 * @return
	 */
	public String saveItems (String mcid ,String data, String customerno, String productid, String jsfs, String yczd, String mysf, String ydwt, String jlid) {
		JSONObject returnInfo = new JSONObject();
		CCService cs = new CCService(userInfo);
        JSONArray items = JSONArray.fromObject(data);
        
        /**
         * 林贵美 2019-03-15
         * 保存更新MC信息
         */
        try {
            List<CCObject> AccountList = cs.cquery("Account","acountnum='"+customerno+"'");//客户信息
            List<CCObject> mcbaseinfoList = cs.cquery("mcbaseinfo","customername='"+AccountList.get(0).get("id").toString()+"' and id='"+mcid+"'");//MC信息
            CCObject oppmcbaseinfo = new CCObject("mcbaseinfo");//MC信息
            if (mcbaseinfoList.size() > 0) {
                oppmcbaseinfo = (CCObject)mcbaseinfoList.get(0);
            }
            oppmcbaseinfo.put("customername",AccountList.get(0).get("id").toString());//客户名称
            oppmcbaseinfo.put("itemdescription",productid);//货品名称
            oppmcbaseinfo.put("chargetype",jsfs);//结算方式
            oppmcbaseinfo.put("remotediagnostics",yczd);//有无远程诊断
            oppmcbaseinfo.put("remotefee",mysf);//远程诊断每月收费
            oppmcbaseinfo.put("unifiedcalucation",ydwt);//允许异地委托统一结算
            if (mcbaseinfoList.size() > 0) {
                cs.update(oppmcbaseinfo);
            } else {
                ServiceResult rs = cs.insert(oppmcbaseinfo);//插入记录
                mcid = rs.get("id")==null?"":rs.get("id").toString();
                List<CCObject> quotedetailList = cs.cquery("quotedetail","id='"+jlid+"'");//报价单明细
                if (quotedetailList.size() > 0) {
                    quotedetailList.get(0).put("mcid",mcid);//MC
                    cs.update(quotedetailList.get(0));
                }
            }
        } catch (Exception ex) {
			ex.printStackTrace();
			returnInfo.put("success", false);
			returnInfo.put("msg", "");
			returnInfo.put("data", "[]");
		}
        
		
		List<CCObject> mcItemList_insert = new ArrayList<CCObject>();
		List<CCObject> mcItemList_update = new ArrayList<CCObject>();
		CCObject mcBaseInfo = new CCObject("mcmasterdata");
		if (items.size() > 0) {
			/**
			 * 查询该MC下的等级收费信息，如果存在，则执行更新，不存在直接创建新的等级收费信息
			 */
			List<CCObject> mxDetailItems = cs.cquery("mcgrade","mcno='" + mcid + "'");
			
			for (int i=0; i<items.size(); i++) {
				CCObject item = new CCObject("mcgrade");
				boolean uflg = false;
				String prodmcItemId = (String)items.getJSONObject(i).get("mcdetailid");
				String mcmainid = (String)items.getJSONObject(i).get("mcid");
				//查找产品MC主数据
				List<CCObject> prodMcList = cs.cquery("mcmasterdata","id='"+mcmainid+"'");//MC主数据
				 //查找产品MC明细主数据，根据张数区间匹配，创建或者更新MC等级收费信息
				List<CCObject> prodMcDetails = cs.cquery("mcdetailinformatio","id='" + prodmcItemId + "'");//MC明细主数据
				if (prodMcDetails.size() > 0 && prodMcList.size() > 0) {
					String pmid = (String)prodMcDetails.get(0).get("id");
						String sqty = (String)prodMcDetails.get(0).get("startingintervalbegins");
						String eqty = (String)prodMcDetails.get(0).get("endofstartinginterval");
						String mtype = (String)prodMcDetails.get(0).get("metertype");
						/**
						 * 产品MC及明细主数据相关信息赋值
						 */
						item.put("tdvstandard", decimal0Format(prodMcList.get(0).get("monthlyestimate")));//月估印量
						item.put("unifiedcalucationcost", prodMcList.get(0).get("allopatrysettlement"));//允许异地委托标志
						item.put("basicalfee", decimal2Format(prodMcList.get(0).get("basicfee")));//基本费
						item.put("standardsalesprice", decimal4Format(prodMcDetails.get(0).get("standardprice")));
						item.put("directservicecost", prodMcList.get(0).get("directservicecost"));//直接服务成本
						item.put("startqty", decimal0Format(prodMcDetails.get(0).get("startingintervalbegins")));//区间起始
						item.put("endqty", decimal0Format(prodMcDetails.get(0).get("endofstartinginterval")));//区间结束
						item.put("includedpaperqty", decimal0Format(prodMcList.get(0).get("containnumber")));//包含张数
						item.put("salesbottomlineprice", decimal4Format((prodMcList.get(0).get("specialofferprice"))));//特价申请底价
						item.put("metertype", prodMcDetails.get(0).get("metertype"));//计费方式
                        item.put("cgjbfwdj", "等级"+prodMcDetails.get(0).get("hierarchy"));//超过基本费外等级 林贵美 2019-04-19新增字段以及赋值
						if (mxDetailItems.size() > 0) {
							for (CCObject mcDetailItem : mxDetailItems) {
								String metertype = (String)mcDetailItem.get("metertype");
								String startqty = (String)mcDetailItem.get("startqty");
								String endqty = (String)mcDetailItem.get("endqty");
								if (mtype.equals(metertype) && sqty.equals(startqty) && eqty.equals(endqty)) {
									item.put("id", mcDetailItem.get("id"));
									uflg = true;
									break;
								}
							}
						}
				}
				//销售信息赋值
				item.put("salespaperqty", decimal0Format(items.getJSONObject(i).get("includedpaperqty")));
				if (items.getJSONObject(i).get("displayno") != null){item.put("displayno",items.getJSONObject(i).get("displayno"));}
				item.put("salesfee", decimal2Format(items.getJSONObject(i).get("basicalfee")));
				item.put("salesprice", decimal4Format(items.getJSONObject(i).get("salesprice")));
				item.put("mcno", mcid);
				if(uflg) {
					mcItemList_update.add(item);
				} else {
					mcItemList_insert.add(item);
				}
			}
			
			if(mcItemList_update.size() > 0) {
				cs.update(mcItemList_update);
			}
			
			if(mcItemList_insert.size() > 0) {
				try {
					cs.insert(mcItemList_insert);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			returnInfo.put("success", true);
			returnInfo.put("msg", "");
			returnInfo.put("data","[]");
		} else {
            cs.cqlQuery("mcgrade","DELETE from mcgrade where mcno='" + mcid + "'");
            returnInfo.put("success", true);
			returnInfo.put("msg", "");
			returnInfo.put("data","[]");
        }
		System.out.println(returnInfo);
		return returnInfo.toString();
	}
	
	public String decimal2Format (Object val) {
		if (val == null || "".equals(val)) {
			return "0.00";
		} else {
			BigDecimal bval = new BigDecimal(String.valueOf(val));
			DecimalFormat df = new DecimalFormat("#0.00");
			return df.format(bval);
		}
	}
	public String decimal4Format (Object val) {
		if (val == null || "".equals(val)) {
			return "0.0000";
		} else {
			BigDecimal bval = new BigDecimal(String.valueOf(val));
			DecimalFormat df = new DecimalFormat("#0.0000");
			return df.format(bval);
		}
	}
	public String decimal0Format (Object val) {
		if (val == null || "".equals(val)) {
			return "0";
		} else {
			BigDecimal bval = new BigDecimal(String.valueOf(val));
			DecimalFormat df = new DecimalFormat("#0");
			return df.format(bval);
		}
	}
}
